Interleaving String
Question
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 ="aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
Analysis
对于
s1 = a1, a2 ……..a(i-1), ai
s2 = b1, b2, …….b(j-1), bj
s3 = c1, c3, …….c(i+j-1), c(i+j)
定义 match[i][j] 意味着,S1的(0, i)和S2的(0,j),匹配与S3的(i+j)
如果 ai == c(i+j), 那么 match[i][j] = match[i-1][j], 等价于如下字符串是否匹配。
s1 = a1, a2 ……..a(i-1)
s2 = b1, b2, …….b(j-1), bj
s3 = c1, c3, …….c(i+j-1)
同理,如果bj = c(i+j), 那么match[i][j] = match[i][j-1];
转移方程如下:
|
|
Code
|
|
Decode Ways
Question
A message containing letters from A-Z is being encoded to numbers using the following mapping:
|
|
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).
The number of ways decoding “12” is 2.
Analysis
一开始考虑用一个数组来记录不同的组合数,后来发现当前i的decode way只与i-1、i-2的decode way个数有关,所以可以用r1,r2两个变量来记录。
- 若字符i为0,由于此时字符i不能独立拆分,所以r1=0
- 若当前字符可以之前字符组合,则r1=r1+r2,r2=r1(原)
- 若当前字符不可组成字符组合,当前字符decode way个数不变,r1不变,r2向前移动(r2=r1)
Code
|
|